//! 同步原语模块
//! 
//! 提供线程安全的同步原语

use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};

/// 自旋锁
pub struct SpinLock {
    locked: AtomicBool,
}

impl SpinLock {
    /// 创建新的自旋锁
    pub const fn new() -> Self {
        SpinLock {
            locked: AtomicBool::new(false),
        }
    }
    
    /// 获取锁
    pub fn lock(&self) {
        while self.locked.compare_and_swap(false, true, Ordering::Acquire) {
            // 自旋等待
            core::hint::spin_loop();
        }
    }
    
    /// 尝试获取锁
    pub fn try_lock(&self) -> bool {
        self.locked.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_ok()
    }
    
    /// 释放锁
    pub fn unlock(&self) {
        self.locked.store(false, Ordering::Release);
    }
}

/// 信号量
pub struct Semaphore {
    count: AtomicU32,
    max_count: u32,
}

impl Semaphore {
    /// 创建新的信号量
    pub const fn new(initial: u32, max: u32) -> Self {
        Semaphore {
            count: AtomicU32::new(initial),
            max_count: max,
        }
    }
    
    /// 等待信号量（P操作）
    pub fn wait(&self) {
        loop {
            let current = self.count.load(Ordering::Acquire);
            if current > 0 {
                if self.count.compare_exchange(current, current - 1, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
                    break;
                }
            }
            core::hint::spin_loop();
        }
    }
    
    /// 尝试等待信号量
    pub fn try_wait(&self) -> bool {
        let current = self.count.load(Ordering::Acquire);
        if current > 0 {
            self.count.compare_exchange(current, current - 1, Ordering::AcqRel, Ordering::Relaxed).is_ok()
        } else {
            false
        }
    }
    
    /// 释放信号量（V操作）
    pub fn signal(&self) {
        let current = self.count.load(Ordering::Acquire);
        if current < self.max_count {
            self.count.store(current + 1, Ordering::Release);
        }
    }
    
    /// 获取当前信号量计数
    pub fn get_count(&self) -> u32 {
        self.count.load(Ordering::Acquire)
    }
}

/// 读写锁
pub struct RwLock {
    reader_count: AtomicU32,
    writer_lock: SpinLock,
}

impl RwLock {
    /// 创建新的读写锁
    pub const fn new() -> Self {
        RwLock {
            reader_count: AtomicU32::new(0),
            writer_lock: SpinLock::new(),
        }
    }
    
    /// 获取读锁
    pub fn read(&self) {
        self.writer_lock.lock();
        self.reader_count.fetch_add(1, Ordering::AcqRel);
        self.writer_lock.unlock();
    }
    
    /// 释放读锁
    pub fn read_unlock(&self) {
        self.reader_count.fetch_sub(1, Ordering::AcqRel);
    }
    
    /// 获取写锁
    pub fn write(&self) {
        self.writer_lock.lock();
        while self.reader_count.load(Ordering::Acquire) > 0 {
            core::hint::spin_loop();
        }
    }
    
    /// 释放写锁
    pub fn write_unlock(&self) {
        self.writer_lock.unlock();
    }
}